package com.amir.common.mvp.base;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.amir.common.R;
import com.amir.common.mvp.presenter.IPresenter;
import com.amir.common.mvp.view.IView;
import com.amir.common.utils.AppManager;
import com.amir.common.utils.BaseContents;
import com.amir.common.utils.LogUtils;
import com.amir.common.utils.MyProgressLoading;
import com.amir.common.utils.SPUtils;
import com.amir.common.utils.ToastUtil;
import com.amir.common.weight.CustomRefreshHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;

import java.util.ArrayList;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

public abstract class AbstractBaseFragment<P extends IPresenter, V extends IView> extends Fragment implements
        ActivityMvpDelegateCallback<P, V>, IView {


    public Context mContext;

    private MyProgressLoading mLoading;
    protected P mPresenter;
    private View mRootViewm;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mRootViewm = inflater.inflate(getlayoutId(), null);

        mPresenter = createPresenter();
        mLoading = new MyProgressLoading(mContext, R.style.DialogStyle);


        return mRootViewm;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView(mRootViewm);
        initData(savedInstanceState);
        initListener();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    protected abstract int getlayoutId();


    protected abstract void initView(View rootView);

    protected abstract void initData(@Nullable Bundle savedInstanceState);


    protected void initListener() {
    }

    @Override
    public P getPresenter() {
        return mPresenter;
    }

    @Override
    public P createPresenter() {
        return getPresenter();
    }

    @Override
    public V getMvpView() {
        return (V) this;
    }

    @Override
    public void onError(String string) {
        Message message = new Message();
        message.obj = string;
        message.what = 0;
        mHandler.sendMessage(message);
    }

    @Override
    public void onAgainLogin() {
        mHandler.sendEmptyMessage(1);
    }

    @Override
    public void showLoading() {
        mLoading.show();
    }

    @Override
    public void dismissLoading() {
        try {
            if(mLoading.isShowing()){
                mLoading.dismiss();
            }
        }
        catch (Exception exception){
            exception.printStackTrace();
        }
    }

    @Override
    public void showDialog(@org.jetbrains.annotations.Nullable String mess, int code) {

    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                ToastUtil.Companion.show("接口未正确响应");
            } else {
                SPUtils.Companion.remove(BaseContents.Token);
                AppManager.getAppManager().finishAllActivity();
                try {
                    Class clz = Class.forName("com.example.steward.ui.activitys.logins.LoginActivity");
                    startActivity(new Intent(mContext, clz));
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    SmartRefreshLayout refreshLayout = null;

    protected String getRefreshTag() {
        return getClass().getName();
    }

    public void initRefreshLayout(SmartRefreshLayout refreshLayout) {
        this.refreshLayout = refreshLayout;
        refreshLayout.setDragRate(0.5f);//显示下拉高度/手指真实下拉高度=阻尼效果
        refreshLayout.setReboundDuration(300);//回弹动画时长（毫秒）
        refreshLayout.setEnableRefresh(enableRefresh());//是否启用下拉刷新功能
        refreshLayout.setEnableLoadMore(enableLoadMore());//是否启用上拉加载功能

        refreshLayout.setEnableOverScrollBounce(true);//是否启用越界回弹
        refreshLayout.setEnableAutoLoadMore(true);//是否启用列表惯性滑动到底部时自动加载更多
        refreshLayout.setRefreshHeader(new CustomRefreshHeader(mContext, getRefreshTag()));
        //设置 Footer 为 球脉冲
        ClassicsFooter.REFRESH_FOOTER_NOTHING = "没有更多数据了";
        //设置 Footer 为 球脉冲
        refreshLayout.setRefreshFooter(new ClassicsFooter(mContext));
        refreshLayout.setOnRefreshListener(refreshlayout -> downOnRefresh());
        refreshLayout.setOnLoadMoreListener(refreshlayout -> {
            refreshlayout.finishLoadMore();
            loadMore();
        });

    }

    public void onFinishNoMore() {
        refreshLayout.finishLoadMoreWithNoMoreData();
    }

    public void onLoadMoreFinish(Boolean result) {
        refreshLayout.finishLoadMore(result);
    }

    public void onRefreshFinish(Boolean result) {
        refreshLayout.finishRefresh(result);

    }

    protected boolean enableRefresh() {
        return true;
    }

    protected boolean enableLoadMore() {
        return true;
    }

    /**
     * 下拉刷新
     */
    public void downOnRefresh() {
        new ArrayList<String>();
    }

    /**
     * 上拉加载更多
     */
    public void loadMore() {

    }

    @Override
    public void onDestroyView() {
        if (mPresenter != null) {
            mPresenter.detachView();
        }
        LogUtils.Companion.E(getClass().getSimpleName(), "onDestroyView");
        super.onDestroyView();
    }
}
